using MediatR;
using RBAC.ErrorCode;
using RBAC.Write.Api.Application.Command.ProcurementOrderInfo;
using RBAC.Interstructrue.Base;
using RBAC.Domain.ProcurementManagement;
using System;
using System.Linq;

namespace RBAC.Write.Api.Application.Handler.ProcurementOrderInfo
{
    public class AddProcurementCommandHandler : IRequestHandler<AddProcurementCommands, APIResult<int>>
    {
        private readonly IBaseRepository<ProcurementTable> _repo;

        public AddProcurementCommandHandler(IBaseRepository<ProcurementTable> repo)
        {
            _repo = repo;
        }

        public Task<APIResult<int>> Handle(AddProcurementCommands request, CancellationToken cancellationToken)
        {
            try
            {
                // 基本校验
                if (string.IsNullOrWhiteSpace(request.OrderTheme))
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "订单主题不能为空", Data = 0 });
                if (string.IsNullOrWhiteSpace(request.ProcurementCode))
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "采购单号不能为空", Data = 0 });
                if (string.IsNullOrWhiteSpace(request.VendorName))
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "供应商名称不能为空", Data = 0 });
                if (request.GoodsIds == null || request.GoodsIds.Count == 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "至少选择一个物品", Data = 0 });

                // 唯一性校验：采购单号
                var exists = _repo.GetFirstOrDefault("ProcurementCode = @ProcurementCode AND IsDeleted = 0", new { request.ProcurementCode });
                if (exists != null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "采购单号已存在", Data = 0 });

                // 组装批量实体（按 GoodsIds 生成多条）
                var list = request.GoodsIds.Select(gid => new ProcurementTable
                {
                    OrderTheme = request.OrderTheme,
                    ProcurementCode = request.ProcurementCode,
                    AssociateRequisition = request.AssociateRequisition ?? string.Empty,
                    AssociateSalesOrders = request.AssociateSalesOrders ?? string.Empty,
                    DatePurchase = request.DatePurchase,
                    VendorName = request.VendorName,
                    Contact = request.Contact ?? string.Empty,
                    ContactNumber = request.ContactNumber ?? string.Empty,
                    PurchasingPersonnel = request.PurchasingPersonnel ?? string.Empty,
                    PurchasingDepartment = request.PurchasingDepartment ?? string.Empty,
                    ContactInformation = request.ContactInformation ?? string.Empty,
                    AssociatedProjects = request.AssociatedProjects ?? string.Empty,
                    SettlementMethod = request.SettlementMethod ?? string.Empty,
                    DeliveryAddress = request.DeliveryAddress ?? string.Empty,
                    Remark = request.Remark ?? string.Empty,
                    SalesId = request.SalesId,
                    GoodsId = gid
                }).ToList();

                var affected = _repo.CreateBatch(list);

                return Task.FromResult(new APIResult<int>
                {
                    Code = affected > 0 ? APIEnums.Success : APIEnums.Fail,
                    Msg = affected > 0 ? "新增采购订单成功" : "新增采购订单失败",
                    Data = affected
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new APIResult<int>
                {
                    Code = APIEnums.Fail,
                    Msg = "新增采购订单异常: " + ex.Message,
                    Data = 0
                });
            }
        }
    }
}
